window.api = {$config};

const submitCallback = function () {
    switch (this.readyState){
        case 4:
            if(this.status === 200){
                try {
                    let result = JSON.parse(this.responseText);
                    if(result.error === 0){
                        if('success' in this.option)
                            this.option.success(result.data);
                    } else {
                        if('fail' in this.option)
                            this.option.fail(result.message);
                    }
                    if('complete' in this.option)
                        this.option.complete();
                } catch (e) {
                    if('error' in this.option)
                        this.option.error(this.status);
                    else console.log('服务器响应格式不正确');
                }
            } else {
                if('error' in this.option)
                    this.option.error(this.status);
                else console.log('服务器未成功响应');
            }
            break;
        default : return;
    }
};

const submit = function (option) {
    let xhr = new XMLHttpRequest();
    xhr.option = option;
    xhr.onreadystatechange = submitCallback;
    if('data' in option){
        if(option.data instanceof FormData
            || option.data instanceof URLSearchParams) {
            xhr.open(this.method, this.url);
            xhr.send(option.data);
        } else {
            let params = new URLSearchParams;
            for(let x in option.data)
                params.append(x, option.data[x]);
            if(this.method.toLocaleLowerCase() === 'get'){
                xhr.open(this.method, this.url+'?'+params.toString());
                xhr.send();
            } else {
                xhr.open(this.method, this.url);
                xhr.send(params);
            }
        }
    }
    else{
        xhr.open(this.method, this.url);
        xhr.send();
    }
};

for(let key in api){
    for(let name in api[key]){
        api[key][name].submit = submit;
    }
}